<?php

namespace App\Services\Plan;

use App\Models\UserPlanModel;
use App\Services\BaseServices;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Throwable;

class PlanServices extends BaseServices
{

    /**
     * 创建待办.
     *
     * @param Request $request
     * @return bool
     */
    public function createPlan(Request $request): bool
    {
        $uId = $request->user()->id;
        $planType = $request->input('plan_type');
        $type = $request->input('type');
        $everyday = $request->input('every_day', 0);
        $content = $request->input('content');
        $unFinishContent = $request->input('un_finish_content');
        $unFinishReason = $request->input('un_finish_reason');
        $improvementPlan = $request->input('improvement_plan');
        $startDate = null;
        $endDate = null;
        $workDate = null;

        if (!isset($planType)) {
            $this->setCustomError('缺少参数: 计划类型');
            return false;
        }

        if (!isset($type)) {
            $this->setCustomError('缺少参数: 类型');
            return false;
        }

        if (!isset($content)) {
            $this->setCustomError('缺少参数: 内容');
            return false;
        }

        if ((int)$type === 2) {
            if (!isset($unFinishContent)) {
                $this->setCustomError('缺少参数: 未完成内容');
                return false;
            }
            if (!isset($unFinishReason)) {
                $this->setCustomError('缺少参数: 未完成原因');
                return false;
            }
            if (!isset($improvementPlan)) {
                $this->setCustomError('缺少参数: 改进计划');
                return false;
            }
        }

        if ((int)$planType === 1 && (int)$everyday === 0) {
            $workDate = Carbon::now()->format('Y-m-d');
        }

        if (in_array((int)$planType, [3, 4, 5])) {
            $now = Carbon::now();
            if ((int)$planType === 3) {
                //周
                $startDate = $now->startOfDay()->format('Y-m-d');
                $endDate = $now->endOfWeek()->format('Y-m-d');
            } elseif ((int)$planType === 4) {
                //月
                $startDate = $now->startOfMonth()->format('Y-m-d');
                $endDate = $now->endOfMonth()->format('Y-m-d');
            } elseif ((int)$planType === 5) {
                //年
                $startDate = $now->startOfYear()->format('Y-m-d');
                $endDate = $now->endOfYear()->format('Y-m-d');
            }
        }

        $model = UserPlanModel::getInstance();

        DB::beginTransaction();
        try {
            $model->u_id = $uId;
            $model->plan_type = $planType;
            $model->type = $type;
            $model->content = $content;
            if (isset($startDate, $endDate)) {
                $model->start_date = $startDate;
                $model->end_date = $endDate;
            }
            $model->every_day = $everyday;
            if (isset($unFinishContent, $unFinishReason, $improvementPlan)) {
                $model->improvement_plan = $improvementPlan;
                $model->un_finish_content = $unFinishContent;
                $model->un_finish_reason = $unFinishReason;
            }
            if (isset($workDate)) {
                $model->work_date = $workDate;
            }

            $model->save();
            DB::commit();
        } catch (Throwable $e) {
            DB::rollBack();
            $this->setCustomError('保存失败');

            return false;
        }

        return true;
    }

    /**
     * 列表
     *
     * @param Request $request
     * @return array
     */
    public function planList(Request $request): array
    {
        $planType = (int)$request->input('plan_type', 0);
        $name = $request->input('name');
        $uId = $request->user()->id;
        $arr = [];

        $modelBase = UserPlanModel::getInstance()->where(['u_id' => $uId])->where(['plan_type' => $planType]);

        if (isset($name)) {
            $modelBase = $modelBase->where('content', 'like', '%' . $name . '%');
        }

        //计划类型: 0 今日待办 1 明日计划 2 周计划 3 月计划 4 年计划
        if ($planType === 1) {
            $start_date = Carbon::now()->addDay()->format('Y-m-d');
            $modelBase = $modelBase->whereDate('created_at', Carbon::now())->where(['every_day' => 1])->orWhereDate('work_date', $start_date);
        } elseif ($planType === 2) {
            $start_date = Carbon::now()->startOfWeek()->format('Y-m-d');
            $end_date = Carbon::now()->endOfWeek()->format('Y-m-d');
            $modelBase = $modelBase->whereDate('created_at', '>=', $start_date)->whereDate('created_at', '<=', $end_date);
        } elseif ($planType === 3) {
            $start_date = Carbon::now()->startOfMonth()->format('Y-m-d');
            $end_date = Carbon::now()->endOfMonth()->format('Y-m-d');
            $modelBase = $modelBase->whereDate('created_at', '>=', $start_date)->whereDate('created_at', '<=', $end_date);
        } elseif ($planType === 4) {
            $start_date = Carbon::now()->startOfYear()->format('Y-m-d');
            $end_date = Carbon::now()->endOfYear()->format('Y-m-d');
            $modelBase = $modelBase->whereDate('created_at', '>=', $start_date)->whereDate('created_at', '<=', $end_date);
        }


        $arr['wait']['title'] = '';
        $arr['wait']['color'] = '#E0A054';
        $arr['wait']['contentColor'] = '#FFC178';
        if ($planType === 0) {
            $arr['wait']['data'] = (clone $modelBase)->where(['type' => 0])
                ->orWhereDate('work_date', Carbon::now()->format('Y-m-d'))
                ->orWhere('every_day', 1)
                ->get()->toArray();
        } else {
            $arr['wait']['data'] = (clone $modelBase)->where(['type' => 0])->get()->toArray();
        }

        if ($planType === 1) {
            return $arr;
        }

//        $arr['finish']['flag'] = [
//            'title' => '已完成项',
//            'color' => '#29c05d',
//            'contentColor' => '#ebfbf2'
//        ];
        $arr['finish']['title'] = '已完成项';
        $arr['finish']['color'] = '#29C05D';
        $arr['finish']['contentColor'] = '#79E2A9';
        $arr['finish']['data'] = (clone $modelBase)->where(['type' => 1])->get()->toArray();

        $arr['un_finish']['title'] = '未完成项';
        $arr['un_finish']['color'] = '#FF6C6C';
        $arr['un_finish']['contentColor'] = '#FFB8C1';
        $arr['un_finish']['data'] = (clone $modelBase)->where(['type' => 2])->get()->toArray();

        if ($planType !== 0) {
            return $arr;
        }

        $arr['happy']['title'] = '开心的事';
        $arr['happy']['color'] = '#29C05D';
        $arr['happy']['contentColor'] = '#79E2A9';
        $arr['happy']['data'] = (clone $modelBase)->where(['type' => 3])->get()->toArray();


        $arr['upset']['title'] = '烦心的事';
        $arr['upset']['color'] = '#FF6C6C';
        $arr['upset']['contentColor'] = '#FFB8C1';
        $arr['upset']['data'] = (clone $modelBase)->where(['type' => 4])->get()->toArray();

        $arr['learn']['title'] = '学到了什么';
        $arr['learn']['color'] = '#29C05D';
        $arr['learn']['contentColor'] = '#79E2A9';
        $arr['learn']['data'] = (clone $modelBase)->where(['type' => 5])->get()->toArray();

        $arr['improvement']['title'] = '需要改进的';
        $arr['improvement']['color'] = '#E0A054';
        $arr['improvement']['contentColor'] = '#FFC178';
        $arr['improvement']['data'] = (clone $modelBase)->where(['type' => 6])->get()->toArray();

        return $arr;
    }

    /**
     * 完成待办事项.
     *
     * @param Request $request
     * @return bool
     */
    public function completePlan(Request $request): bool
    {
        $id = $request->input('id');

        $info = UserPlanModel::getInstance()->find($id);
        if (!$info) {
            $this->setCustomError('待办事项不存在');
            return false;
        }

        if ((int)$info->type !== 0) {
            $this->setCustomError('当前待办事项不支持该操作');
            return false;
        }

        try {
            $info->type = 1;
            $info->save();
        } catch (Exception $e) {
            $this->setCustomError();
            return false;
        }

        return true;
    }

    /**
     * 删除.
     *
     * @param Request $request
     * @return bool
     */
    public function delPlan(Request $request): bool
    {
        $id = $request->input('id');

        $info = UserPlanModel::getInstance()->find($id);
        if (!$info) {
            $this->setCustomError('数据不存在');
            return false;
        }

        try {
            $info->delete();
        } catch (Exception $e) {
            $this->setCustomError();
            return false;
        }

        return true;
    }
}
